const getHeaderToken = () => {
  const token = wx.getStorageSync('token') || undefined;
  return `Bearer ${token}`
}
const API_HOST = "https://hmthm.joymew.com/"
// const API_HOST = "http://192.168.66.39:8032/"
class Http {
  constructor() {
    // requestQueue：请求队列、数据项格式举例：{url,method,data,loadingText,resolve}
    // isRelogin：重新登录标识、数据类型:boolean、使用场景：token过期需要重新登录
    this.requestQueue = [];
    this.isRelogin = false;
  }
  request(url, method = 'GET', data, loadingText = '') {
    return new Promise((resolve, reject) => {
      if (loadingText) {
        wx.showLoading({
          title: loadingText,
          mask: true,
        });
      }
      wx.request({
        url: API_HOST + url,
        method,
        timeout: 10000,
        header: {
          'Authorization': getHeaderToken(),
          'appid': 'wx7239c7a2397fb19c',
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data,
        success: async (res) => {
          if (loadingText) {
            wx.hideLoading()
          }
          if (res.statusCode === 200) {
            if (res.data.msg == '401 UNAUTHORIZED') {
              console.log('request on 401')
              // 请求暂存队列
              this.joinQueue({
                url,
                method,
                data,
                loadingText,
                resolve
              })
              // 限制登录的频次
              if (this.isRelogin) {
                return;
              }
              this.isRelogin = true
              // 授权登录重新获取token
              const authRes = await getApp().Login()
              console.log('401 then reLogin', authRes.token)
              // 如果返回token表示授权登录成功
              // 1、重置”重新登录的标记“ 2、重新发起等待队列中的请求
              // 否则 授权登录失败(极端情况)
              if (authRes.token) {
                this.isRelogin = false
                this.resendQueueRequest()
              } else {
                reject('网络异常-reLogin err')
                wx.showToast({
                  title: '网络异常-reLogin err',
                  icon: 'none'
                })
              }
            } else {
              resolve(res.data)
            }
          } else {
            console.log(res)
            reject('网络异常-not 200')
            wx.showToast({
              title: '网络异常-not 200',
              icon: 'none'
            })
          }
        },
        fail: err => {
          if (loadingText) {
            wx.hideLoading()
          }
          console.log(err)
          reject('网络异常')
        },
      })

    })
  }

  post(url, data, loadingText = '') {
    return this.request(url, 'POST', data, loadingText)
  }

  get(url, data, loadingText = '') {
    return this.request(url, 'GET', data, loadingText)
  }
  // 请求暂存队列
  joinQueue(requestObj) {
    this.requestQueue.push(requestObj)
  }
  // 重新发起队列里暂存的请求
  resendQueueRequest() {
    this.requestQueue.forEach(async (requestObj) => {
      const {
        url,
        method,
        data,
        loadingText,
        resolve
      } = requestObj
      const requestRes = await this.request(url, method, data, loadingText)
      console.log('reRequestRes', requestRes)
      resolve(requestRes)
    })
  }
}

export default new Http()